package user

import (
	"context"
	"encoding/json"
	"errors"
	"hzjt-oam/rpc/sys/pb"
	"strings"

	"hzjt-oam/admin/internal/svc"
	"hzjt-oam/admin/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type ReSetPasswordLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewReSetPasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ReSetPasswordLogic {
	return &ReSetPasswordLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ReSetPasswordLogic) ReSetPassword(req *types.ReSetPasswordReq) (resp *types.ReSetPasswordResp, err error) {
	if len(strings.TrimSpace(req.Password)) == 0 {
		reqStr, _ := json.Marshal(req)
		logx.WithContext(l.ctx).Errorf("密码不能为空,请求信息失败,参数:%s", reqStr)
		return nil, errors.New("用户名或密码不能为空")
	}

	userId, err := l.ctx.Value("userId").(json.Number).Int64()
	if err != nil {
		return nil, errors.New("验证token未通过")
	}

	user_one, err := l.svcCtx.UserSrv.GetSysUserById(l.ctx, &pb.GetSysUserByIdReq{
		Id: int64(userId),
	})
	_, err = l.svcCtx.UserSrv.ReSetPassword(l.ctx, &pb.ReSetPasswordReq{
		Id:           req.Id,
		Password:     req.Password,
		LastUpdateBy: user_one.SysUser.Name,
	})

	if err != nil {
		logx.WithContext(l.ctx).Errorf("重置密码失败:%s", err)
		return nil, errors.New("重置密码失败")
	}

	return &types.ReSetPasswordResp{Message: "成功"}, err
}
